/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年1月27日         cassie
 */

package com.tianci.appstore.ui.list.bootsetting;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.LogUtils;
import com.tianci.appstore.LaunchManageActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.audio.IAudio;
import com.tianci.appstore.controller.manager.BootUpAppManagerController;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListSwitchData;
import com.tianci.appstore.ui.list.ListFlipper;
import com.tianci.appstore.ui.list.ListSwitchBlock;
import com.tianci.appstore.ui.list.SkyListAdapter;
import com.tianci.appstore.ui.list.manage.ManageBaseListView;
import com.tianci.appstore.ui.list.manage.ManageListController;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.SkyAppPager.Direction;
import com.tianci.appstore.ui.widget.SkyCustomLayout;
import com.tianci.appstore.ui.widget.SkyCustomLayout.BlockData;
import com.tianci.appstore.ui.widget.SkyCustomLayout.CustomLayoutParams;
import com.tianci.appstore.utils.SkyConstants;

import java.util.HashMap;
import java.util.List;

public class LaunchOnBootListView extends ManageBaseListView implements
        OnClickListener, LaunchOnBootSettinglistener {
    private LinearLayout btnLayout;
    //private Button launchAllBotton;
    private Button closeAllButton;
    private SkyListAppData mStartApp = null;
    private SkyListSwitchData mSwitchData = null;
    private static final int LAUNCH_ALL_BTN_ID = 101;
    private static final int CLOSE_ALL_BTN_ID = 102;
    private static final String LAUNCHER_LIST = "开机启动应用";

    private List<SkyListSwitchData> dataList;

    public LaunchOnBootListView(Context context) {
        super(context, ListType.LAUNCH_ON_BOOT_LIST);
        LogUtils.d("boot","the new boot is " + hideStartupApp);
        // TODO Auto-generated constructor stub
        initTopRightLayout();
        BootUpAppManagerController.getInstance().init(this);
        setLoadingVisible(true);
        titleText.setVisibility(View.GONE);
        reLayoutArrow();
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER);
        if (!hideStartupApp){
            params.topMargin = CoocaaApplication.Div(240);
        }
        tipText.setLayoutParams(params);
    }

    private void reLayoutArrow() {
        LayoutParams leftParams = null;
        LayoutParams rightParams = null;
        if (!hideStartupApp){
            rightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
            leftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT);
            leftParams.topMargin = SkyConstants.Div(700);
            rightParams.topMargin = SkyConstants.Div(700);
        }else{
            rightParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT|Gravity.CENTER_VERTICAL);
            leftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT|Gravity.CENTER_VERTICAL);
        }
        leftParams.leftMargin = SkyConstants.Div(36);
        rightParams.rightMargin = SkyConstants.Div(36);
        leftArrow.setLayoutParams(leftParams);
        rightArrow.setLayoutParams(rightParams);
    }

    private void initTopRightLayout() {
//        LinearLayout rightTopLayout = new LinearLayout(mContext);
//        rightTopLayout.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
        btnLayout = new LinearLayout(mContext);
        LayoutParams topRightParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT);
        topRightParams.setMargins(0, SkyConstants.Div(87), SkyConstants.Div(111), 0);
        this.addView(btnLayout, topRightParams);

        // launchAllBotton = newButton(LAUNCH_ALL_BTN_ID, R.string.launch_all_on_boot);
        closeAllButton = newButton(CLOSE_ALL_BTN_ID, R.string.close_all);
//        btnLayout.addView(launchAllBotton, new LinearLayout.LayoutParams(
//                LayoutParams.MATCH_PARENT, SkyConstants.Div(80)));
        LinearLayout.LayoutParams sndBtnParams = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, SkyConstants.Div(113));
        sndBtnParams.leftMargin = SkyConstants.Div(20);
        btnLayout.addView(closeAllButton, sndBtnParams);
    }

    public void setStartApp(SkyListAppData appData) {
        this.mStartApp = appData;
    }

    public void refreshStartApp(SkyListAppData appData) {
        if (!appData.getPkgName().equals(mStartApp.getPkgName())) {
            this.mStartApp = appData;
            if (mSwitchData != null) {
                dataList.add(mSwitchData);
            }
            removeStartApp(dataList);
            Message msg = mainHandler.obtainMessage(UPDATE_LIST);
            msg.obj = dataList;
            mainHandler.sendMessage(msg);
        }
        this.mStartApp = appData;
    }

    @Override
    protected void initFlipper() {
        int row = 3;
        if (!hideStartupApp){
            row = 2;
        }
        int column = 4;
        listFlipper = new ListFlipper(mContext, Direction.HORIZONTAL);
        mController = new ManageListController(mContext, listFlipper, row, column);
        mController.setAudioMatchListener(this);
        List<BlockData> blockDataList = createListBlockData(row, column);
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout page = new SkyCustomLayout(mContext, CoocaaApplication.mDiv);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
            page.setLayoutParams(params);
            CustomLayoutParams netAppParams = new CustomLayoutParams();
            netAppParams.mRow = row;
            netAppParams.mCol = column;
            netAppParams.mBlockWidth = SkyConstants.Div(472);
            netAppParams.mBlockHeight = SkyConstants.Div(280);
            netAppParams.mHorizontalSpace = SkyConstants.Div(-47);
            netAppParams.mVerticalSpace = SkyConstants.Div(-36);
            if (!hideStartupApp){
                netAppParams.mMarginTop = SkyConstants.Div(510);
            }else{
                netAppParams.mMarginTop = SkyConstants.Div(210) - SkyConstants.shadowWidth;
            }
            page.setCustomLayoutParams(netAppParams);
            page.setBlockDatas(blockDataList);
            SkyListAdapter mAdapter = new SkyListAdapter(mContext, listType, i, CoocaaApplication.mDiv);
            mAdapter.setKeyListener(mController);
            mAdapter.setOnItemClickListener(this);
            mAdapter.setMultiSelectListener(mController);
            mAdapter.setItemSelectableListener(this);
            page.setAdapter(mAdapter);
            listFlipper.addView(page);
        }
        FrameLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        params.leftMargin = CoocaaApplication.Div(90);
        contentLayout.addView(listFlipper, params);
    }

    private Button newButton(int btnId, int strId) {
        Button btn = UICommon.newButton(mContext, rightTopTextSize, R.color.btnColor);
        SkinManager.setBackground(btn, R.drawable.search_selector);
        btn.setPadding(SkyConstants.Div(40), 0, SkyConstants.Div(40), SkyConstants.Div(6));
        btn.setText(strId);
        btn.setId(btnId);
        btn.setOnClickListener(this);
        return btn;
    }

    @Override
    public void onBlockClicked(View v, SkyListAppData data, int index) {
        // TODO Auto-generated method stub
        SkyListSwitchData switchData = (SkyListSwitchData) data;
        LogUtils.d("boot_setting", data.getTitle() + " clicked, setLaunch = " + !switchData.isSwitchOn());
        BootUpAppManagerController.getInstance().setOneEnable(
                switchData, !switchData.isSwitchOn());
    }

    @Override
    public void destroyController() {
        // TODO Auto-generated method stub
        BootUpAppManagerController.getInstance().destroy();
        super.destroyController();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case LAUNCH_ALL_BTN_ID:
                LogUtils.d("boot_setting", "set all enabled!!!!!!");
                BootUpAppManagerController.getInstance().setAllEnable(true);
                break;
            case CLOSE_ALL_BTN_ID:
                LogUtils.d("boot_setting", "set all disabled!!!!!!");
                BootUpAppManagerController.getInstance().setAllEnable(false);
                break;
        }
    }

    @Override
    public void onLaunchAppListLoaded(List<SkyListSwitchData> dataList) {
        // TODO Auto-generated method stub
        if (dataList != null)
            LogUtils.d("boot_setting", "Launch app list loaded, size = " + dataList.size());
        else
            LogUtils.d("boot_setting", "Launch app list loaded, size = 0");
        removeStartApp(dataList);
        this.dataList = dataList;
        Message msg = mainHandler.obtainMessage(UPDATE_LIST);
        msg.obj = dataList;
        mainHandler.sendMessage(msg);
    }

    private void removeStartApp(List<SkyListSwitchData> dataList) {
        if (!mStartApp.getPkgName().equals("") && dataList != null && dataList.size() > 0) {
            SkyListSwitchData temp = null;
            for (SkyListSwitchData appData : dataList) {
                if (mStartApp.getPkgName().equals(appData.getPkgName())) {
                    temp = appData;
                    break;
                }
            }
            if (temp != null) {
                mSwitchData = temp;
                if (!mSwitchData.isSwitchOn()) {
                    BootUpAppManagerController.getInstance().setOneEnable(
                            mSwitchData, true);
                }
                dataList.remove(temp);
            } else {
                mSwitchData = null;
            }
        } else {
            mSwitchData = null;
        }
    }

    @Override
    public void onAppLaunchStatusChanged(SkyListSwitchData data) {
        // TODO Auto-generated method stub
        if (data != null)
            LogUtils.d("boot_setting", data.getTitle() + " launch status changed, launch = " + data.isSwitchOn());
        else
            LogUtils.d("boot_setting", "!!!!!!!! app launch status changed, but data = null");
        Message msg = mainHandler.obtainMessage(UPDATE_STATUS);
        msg.obj = data;
        mainHandler.sendMessage(msg);
    }

    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_LIST:
                    updateLaunchAppList((List<SkyListAppData>) msg.obj);
                    break;
                case UPDATE_STATUS:
                    refreshAppLaunchStatus((SkyListSwitchData) msg.obj);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void updateLaunchAppList(List<SkyListAppData> dataList) {
        // TODO Auto-generated method stub
        if (dataList == null || dataList.size() == 0) {
            setEmptyTipVisible(true, mContext.getResources().getString(R.string.launch_on_boot_no_app));
            //setBtnEnabled(launchAllBotton, false);
            setBtnEnabled(closeAllButton, false);
            return;
        }

        setLoadingVisible(false);
        setEmptyTipVisible(false, null);
        mController.setDataList(dataList);
        //resetFocus();
    }

    public IAudio getAudioInterface() {
        return mController;
    }

    public void refreshAppLaunchStatus(SkyListSwitchData data) {
        // TODO Auto-generated method stub
        for (int i = 0; i < ListFlipper.VIEW_PAGE_COUNT; i++) {
            SkyCustomLayout child = (SkyCustomLayout) listFlipper.getChildAt(i);
            for (View view : child.getChildViews()) {
                ListSwitchBlock block = (ListSwitchBlock) view;
                if (block.getPkgName() != null && block.getPkgName().equals(data.getPkgName())) {
                    block.update(data);
                    break;
                }
            }
        }
    }

    @Override
    public void onItemAudioMatch(SkyAppBaseData data, int index) {
        SkyListSwitchData switchData = (SkyListSwitchData) data;
        BootUpAppManagerController.getInstance().setOneEnable(
                switchData, !switchData.isSwitchOn());
    }

    @Override
    public void onAudioMatch(String name) {
        if (name.equals(LAUNCHER_LIST)) {
            Intent intent = new Intent();
            intent.setClass(mContext, LaunchManageActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("listType", ListType.SELECTED_LAUNCH_LIST.toString());
            mContext.startActivity(intent);
        }
    }

    @Override
    public HashMap<String, String[]> addExtraCommand(HashMap<String, String[]> current) {
        current.put(LAUNCHER_LIST, new String[]{LAUNCHER_LIST});
        return current;
    }
}
